/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.cef.repository.dbpropertyconvertors;

import com.inspur.edp.cef.repository.exception.CefRepositoryException;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DbPropertyConvertors
{
	public static String convertVarcharToString(Object value)
	{
		if (value == null)
		{
			return null;
		}
		return String.valueOf(value);
	}

	public static int convertIntToInt(Object value)
	{
		if (value == null)
		{
			return 0;
		}
		if(value instanceof Integer)
			return (int)value;
		if(value instanceof  String)
		return Integer.parseInt((String)value);
		throw new CefRepositoryException();
	}

	public static BigDecimal convertDecimalToDecimal(Object value)
	{
		if (value == null)
		{
			return BigDecimal.ZERO;
		}
		if(value instanceof BigDecimal)
			return (BigDecimal)value;
		return new BigDecimal((String)value);
	}

	public static java.util.Date convertDateToDateTime(Object value) throws ParseException {
		if (value == null)
		{
			return new java.util.Date(0);
		}
		if(value instanceof Date)
			return (Date)value;
		if(value instanceof  String)
		{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			Date dateVal = sdf.parse((String)value);
		}
		throw new CefRepositoryException();
	}

	public static boolean convertVarcharToBool(Object value)
	{
		if (value == null)
		{
			return false;
		}
		//return Convert.ToBoolean(value);

		String convertValue = String.valueOf(value);
		if (convertValue.toUpperCase().equals("FALSE") || convertValue.equals("0"))
		{
			return false;
		}
		else if (convertValue.toUpperCase().equals("TRUE") || convertValue.equals("1"))
		{
			return true;
		}
		else
		{
			throw new CefRepositoryException("过滤条件中写入了错误格式的布尔类型数据");
		}
	}

	public static byte[] convertBytesToBinary(Object value)
	{
		throw new UnsupportedOperationException();
	}

	public static String convertTextToString(Object value)
	{
		if (value == null)
		{
			return null;
		}
		return String.valueOf(value);
	}
}
